package com.example.springmall.controller;

import com.example.springmall.common.R;
import com.example.springmall.dto.LoginResponse;
import com.example.springmall.entity.SysUser;
import com.example.springmall.request.LoginRequest;
import com.example.springmall.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/user")
@RequiredArgsConstructor
public class SysUserController {
    private static final String TOKEN_COOKIE_NAME = "token";
    private static final String TOKEN_COOKIE_PATH = "/";
    private static final int TOKEN_COOKIE_MAX_AGE = 24 * 60 * 60; // 24小时，单位：秒

    private final UserService userService;

    @PostMapping("/login")
    public R<LoginResponse> login(@RequestBody LoginRequest loginRequest, HttpServletResponse httpServletResponse) {
        LoginResponse response = userService.login(loginRequest);

        // 设置token到Cookie
        Cookie cookie = new Cookie(TOKEN_COOKIE_NAME, response.getToken());
        cookie.setPath(TOKEN_COOKIE_PATH);
        cookie.setMaxAge(TOKEN_COOKIE_MAX_AGE);
        cookie.setHttpOnly(true);
        httpServletResponse.addCookie(cookie);

        return R.ok(response);
    }

    @PostMapping("/register")
    public R register(@RequestBody SysUser sysUser) {
        userService.register(sysUser);
        return R.ok();
    }

    @PostMapping("/logout")
    public R<Void> logout(HttpServletResponse response) {

        // 清除Cookie中的token
        Cookie cookie = new Cookie(TOKEN_COOKIE_NAME, null);
        cookie.setPath(TOKEN_COOKIE_PATH);
        cookie.setMaxAge(0);
        response.addCookie(cookie);

        return R.ok();
    }

    @PutMapping("/reset-password")
    public R<Void> resetPassword() {
        return R.ok();
    }
} 